import dayjs from "dayjs";
import type { VxeColumnPropTypes, VxeGridPropTypes, VxeTableDefines } from "vxe-table";

export function dateFormat(time: Nullable<Timestamp>, format: string) {
  return time !== null && time !== undefined ? dayjs(time).format(format) : "-";
}

export function getDateTime(time: Nullable<Timestamp>) {
  return dateFormat(time, "YYYY/MM/DD HH:mm:ss");
}
export function getDate(time: Nullable<Timestamp>) {
  return dateFormat(time, "YYYY/MM/DD");
}
export function getTime(time: Nullable<Timestamp>) {
  return dateFormat(time, "HH:mm:ss");
}

export function generateAuditColumns<T>(config?: VxeTableDefines.ColumnOptions & { dateMode: "datetime" | "date" | "time" }): VxeGridPropTypes.Columns<T> {
  let dateFormatter: VxeColumnPropTypes.Formatter<T>;
  let dateWidth: number;
  switch (config?.dateMode) {
    case "date":
      dateFormatter = ({ cellValue }) => getDate(cellValue);
      dateWidth = 100;
      break;
    case "time":
      dateFormatter = ({ cellValue }) => getTime(cellValue);
      dateWidth = 100;
      break;
    case "datetime":
    default:
      dateFormatter = ({ cellValue }) => getDateTime(cellValue);
      dateWidth = 150;
      break;
  }

  const userFormatter: VxeColumnPropTypes.Formatter<T> = ({ cellValue }) => cellValue || "-";
  return [
    { field: "createUser", title: "创建用户", sortable: config?.sortable, width: 100, align: "center", formatter: userFormatter },
    { field: "createAt", title: "创建时间", sortable: config?.sortable, width: dateWidth, align: "center", formatter: dateFormatter },
    { field: "updateUser", title: "更新用户", sortable: config?.sortable, width: 100, align: "center", formatter: userFormatter },
    { field: "updateAt", title: "更新时间", sortable: config?.sortable, width: dateWidth, align: "center", formatter: dateFormatter },
  ];
}
